package com.sjr.easy.chat.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class SHA256 {

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param str 需要加密的数据
     * @return
     */
    public static byte[] crypt(String str) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            return messageDigest.digest();
        } catch (NoSuchAlgorithmException e) {
            log.error("SHA256签名失败:", e);
            throw new RuntimeException("SHA256签名失败");
        }
    }

    public static String cryptToHexString(String str) {
        return Hex.encodeHexString(crypt(str));
    }

    public static String cryptToBase64String(String str) {
        return Base64.encodeBase64String(crypt(str));
    }
}
